package com.cloudkinto.appletservice.orderinput.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.appletservice.orderinput.AppletOrderInputService;
import com.cloudkinto.appletservice.orderinput.vo.AppletOderInputDetailRes;
import com.cloudkinto.appletservice.orderinput.vo.AppletOrderInputPageRes;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.error.ErrorEnum;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.NotSufficientFundsException;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.email.MailSenderService;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.orderinput.vo.*;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.storage.StorageService;
import com.cloudkinto.utils.PdfUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-08
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AppletOrderInputServiceImpl extends ServiceImpl<OrderInputDao, OrderInputDo> implements AppletOrderInputService {
    @Autowired
    private OrderInputDao dao;
    @Autowired
    private FileService fileService;
    @Autowired
    private OrderInputPackageDao orderInputPackageDao;
    @Autowired
    private OrderInputProductDao orderInputProductDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private ShopService shopService;


    //真正的存储路径
    @Value("${gbc.uploadPath.filePath}")
    private String filePath;
    @Autowired
    private MailSenderService mailSenderService;


    @Override
    public AppletOderInputDetailRes detail(Long id) {
        OrderInputDo entityDo = dao.selectById(id);
        AppletOderInputDetailRes res = new AppletOderInputDetailRes();
        ShopDo shopDo = shopDao.selectById(entityDo.getShopId());
        if (shopDo != null) {
            res.setShopName(shopDo.getShopName());
        }
//        res.setShopId(entityDo.getShopId());
//        res.setStorageId(entityDo.getStorageId());
        StorageDo storageDo = storageDao.selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorage(storageDo.getStorageName());
        }
        res.setId(entityDo.getId());
        res.setOrderInputNumber(entityDo.getOrderInputNumber());
        res.setDeliveryDate(entityDo.getDeliveryDate());
        res.setCarriageTrackNo(entityDo.getCarriageTrackNo());
//        res.setCarriageType(entityDo.getCarriageType());
//        DicBusinessItemDo carriageTypeItemDo = dicBusinessItemDao.selectById(entityDo.getCarriageType());
        String carriageTypeItemDo = getInitValueMap().get("carriageType").get(entityDo.getCarriageType().intValue());
        if (carriageTypeItemDo != null) {
            res.setCarriageTypeName(carriageTypeItemDo);
        }
//        res.setSendType(entityDo.getSendType());
//        DicBusinessItemDo sendtypeItemDo = dicBusinessItemDao.selectById(entityDo.getSendType());
        String sendtypeItemDo = getInitValueMap().get("sendType").get(entityDo.getSendType().intValue());
        if (sendtypeItemDo != null) {
            res.setSendTypeName(sendtypeItemDo);
        }
        res.setCarriageTrackNo(entityDo.getCarriageTrackNo());
//        res.setFbaTurn(entityDo.getFbaTurn());
        String fbaTurn = getInitValueMap().get("fbaTurn").get(entityDo.getFbaTurn());
        if (fbaTurn != null) {
            res.setFbaTurnName(fbaTurn);
        }
        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(entityDo.getStatus());
        if (businessItemDo != null) {
            res.setStatus(businessItemDo.getDicItemValue());
        }
//        res.setFbaNo(entityDo.getFbaNo());
//        res.setFbaPo(entityDo.getFbaPo());
//        res.setFbaFileUrl(fileService.getFilePath(entityDo.getFbaFileId()));
//        res.setFbaFileId(entityDo.getFbaFileId());
//        FileDo fileDo = fileService.getBaseMapper().selectById(entityDo.getFbaFileId());
//        if (fileDo != null) {
//            res.setFileName(fileDo.getFileName());
//        }
//        res.setVolume(entityDo.getVolume());
        res.setTips(entityDo.getTips());
        res.setSeaFee(entityDo.getSeaFee());
        res.setClearanceFee(entityDo.getClearanceFee());
        res.setServiceFee(entityDo.getServiceFee());
        res.setTaxFee(entityDo.getTaxFee());


//        List<OrderInputPackageDetail> packageList = new ArrayList<>();
//        LambdaQueryWrapper<OrderInputPackageDo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(OrderInputPackageDo::getOrderInputId, entityDo.getId());
//        List<OrderInputPackageDo> orderInputPackageDos = orderInputPackageDao.selectList(wrapper);
//        if (!CollectionUtils.isEmpty(orderInputPackageDos)) {
//            for (OrderInputPackageDo packageDo : orderInputPackageDos) {
//                OrderInputPackageDetail packageDetail = new OrderInputPackageDetail();
//                packageDetail.setId(packageDo.getId());
//                packageDetail.setCount(packageDo.getPackageCount());
//                packageDetail.setHeight(packageDo.getPackageHeight());
//                packageDetail.setLength(packageDo.getPackageLenght());
//                packageDetail.setWeight(packageDo.getPackageWeight());
//                packageDetail.setWidth(packageDo.getPackageWidth());
//                List<OrderInputProductDetail> productAddList = new ArrayList<>();
//
//                LambdaQueryWrapper<OrderInputProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                productDoLambdaQueryWrapper.eq(OrderInputProductDo::getOrderInputId, entityDo.getId()).eq(OrderInputProductDo::getPackageId, packageDo.getId());
//                List<OrderInputProductDo> orderInputProductDos = orderInputProductDao.selectList(productDoLambdaQueryWrapper);
//                if (!CollectionUtils.isEmpty(orderInputProductDos)) {
//                    for (OrderInputProductDo productDo : orderInputProductDos) {
//                        OrderInputProductDetail productDetail = new OrderInputProductDetail();
//                        ProductInfoDo productInfoDo = productInfoDao.selectById(productDo.getProductId());
//                        if (productInfoDo != null) {
//                            productDetail.setProductId(productInfoDo.getId());
//                            productDetail.setCount(productDo.getCount());
//                            productDetail.setCommoditySku(productInfoDo.getCommoditySku());
//                            productDetail.setProductName(productInfoDo.getProductName());
//                            productDetail.setStorageSku(productInfoDo.getStorageSku());
//                            productAddList.add(productDetail);
//                        }
//                    }
//                }
//                packageDetail.setProductList(productAddList);
//
//                packageList.add(packageDetail);
//
//            }
//        }
//
//        res.setPackageList(packageList);
        return res;
    }

    private Map<String, Map<Integer, String>> getInitValueMap() {

        Map<String, Map<Integer, String>> result = new HashMap<>();

        Map<Integer, String> carriageType = new HashMap();
        carriageType.put(0, "散货");
        carriageType.put(1, "整柜");
        carriageType.put(2, "空运");

        Map<Integer, String> sendType = new HashMap();
        sendType.put(0, "自发头程");
        sendType.put(1, "筋斗云头程");

        Map<Integer, String> fbaTurn = new HashMap();
        fbaTurn.put(0, "否");
        fbaTurn.put(1, "是");

        Map<Integer, String> status = new HashMap();
        status.put(-1, "驳回");
        status.put(0, "已下单");
        status.put(1, "已审核");
        status.put(2, "待入库");
        status.put(3, "已入库");
        status.put(4, "已上架");

        result.put("carriageType", carriageType);
        result.put("sendType", sendType);
        result.put("fbaTurn", fbaTurn);
        result.put("status", status);

        return result;
    }

    @Override
    public SingleResult pageInit(Long userId, Long companyId) {
        Map result = new HashMap();
//        result.put("shopList", shopService.selectShopListInit(userId, companyId));

        List<Map> statusList = new ArrayList<>();

        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.inPutStatus);
        List<DicBusinessItemDo> sendOutType = dicBusinessItemDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(sendOutType)) {
            sendOutType.forEach(e -> {
                Map map = new HashMap();
                map.put("id", e.getId());
                map.put("value", e.getDicItemValue());
                statusList.add(map);
            });
        }

        result.put("statusList", statusList);
        return SingleResult.success(result);
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<OrderInputDo> wrapper = queryBuild(map);
        IPage<OrderInputDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<AppletOrderInputPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        result.setMapInfo(census(map));
        return result;
    }


    //统计信息
    private Map census(Map<String, String> wrapper) {
        List<Map> result = new ArrayList<>();
        Map mapTotal = new HashMap();
        int total = dao.selectCount(queryBuild(wrapper));
        mapTotal.put("count", total);
        mapTotal.put("name", "全部");
        mapTotal.put("id", null);
        result.add(mapTotal);
        LambdaQueryWrapper<DicBusinessItemDo> businessItemDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        businessItemDoLambdaQueryWrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.inPutStatus);
        List<DicBusinessItemDo> businessItemDoList = dicBusinessItemDao.selectList(businessItemDoLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(businessItemDoList)) {
            for (DicBusinessItemDo itemDo : businessItemDoList) {
                wrapper.put("status", itemDo.getId() + "");
                Map map = new HashMap();
                int count = dao.selectCount(queryBuild(wrapper));
                map.put("count", count);
                map.put("name", itemDo.getDicItemValue());
                map.put("id", itemDo.getId());
                result.add(map);
            }
        }
        Map map = new HashMap();
        map.put("census", result);
        return map;
    }

    //查询分页列表之后对列表数据的处理
    private List<AppletOrderInputPageRes> handlerListAfter(List<OrderInputDo> list) {
        List<AppletOrderInputPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (OrderInputDo orderInputDo : list) {
                AppletOrderInputPageRes res = new AppletOrderInputPageRes();
                res.setId(orderInputDo.getId());
                res.setCarriageTrackNo(orderInputDo.getCarriageTrackNo());
//                CompanyDo companyDo = companyDao.selectById(orderInputDo.getCompanyId());
//                if (companyDo != null) {
//                    res.setCompanyName(companyDo.getName());
//                }
                res.setCreateTime(orderInputDo.getCreateTime());
                res.setDeliveryDate(orderInputDo.getDeliveryDate());
//                ShopDo shopDo = shopDao.selectById(orderInputDo.getShopId());
//                if (shopDo != null) {
//                    res.setShopName(shopDo.getShopName());
//                }
                res.setOrderInputNumber(orderInputDo.getOrderInputNumber());
                StorageDo storageDo = storageDao.selectById(orderInputDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                res.setTips(orderInputDo.getTips());
                res.setVolume(orderInputDo.getVolume());
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(orderInputDo.getStatus());
                if (businessItemDo != null) {
                    res.setStatus(businessItemDo.getDicItemValue());
                }

                result.add(res);
            }
        }
        return result;
    }

    private IPage<OrderInputDo> pageInit(Map<String, String> map) {
        IPage<OrderInputDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<OrderInputDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OrderInputDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> i.like("order_input_number", map.get("keyword"))
                    .or().like("carriage_track_no", map.get("keyword"))
                    .or().like("tips", map.get("keyword")));
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        wrapper.eq("company_id", map.get("companyId")).orderByDesc("id");
        return wrapper;
    }

}
